package com.shuma.loggingservice.listener;

import com.rabbitmq.client.Channel;
import com.shuma.common.event.OperationLogEvent;
import com.shuma.loggingservice.config.LogMqConfig;
import com.shuma.loggingservice.mapper.OperationLogsMapper;
import com.shuma.loggingservice.pojo.OperationLogs;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
@RequiredArgsConstructor
public class LogMessageListener {

    private final OperationLogsMapper logMapper;

    @RabbitListener(queues = LogMqConfig.QUEUE)
    public void handle(OperationLogEvent event, Channel channel, Message message) throws IOException {
        try {
            OperationLogs log = new OperationLogs();
            log.setUserId(event.getUserId());
            log.setAction(event.getAction());
            log.setIp(event.getIp());
            log.setDetail(event.getDetail());
            log.setGmtCreate(new Date());
            logMapper.insert(log);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
